<?php
declare(strict_types=1);

namespace App\Middleware;


use App\Constants\ErrorCode;
use App\Model\form\SellerTrait;
use Hyperf\Context\Context;
use HyperfException\Json;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;

class TokenMiddleware implements MiddlewareInterface
{
    use SellerTrait;

    /**
     * @var ContainerInterface
     */
    protected $container;

    protected $url = [];

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    /**
     * @param ServerRequestInterface $request
     * @param RequestHandlerInterface $handler
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        /*判断是否验证token*/
        $params = $request->getParsedBody();
        if (empty($params['token']))
            throw new json(ErrorCode::getMessage(ErrorCode::ERROR), ErrorCode::ERROR);
        $token = trim($params['token']);
        $sellerInfo = $this->getSellerInfo(['token' => $token]);
        if (empty($sellerInfo)) {
            throw new json(ErrorCode::getMessage(ErrorCode::ERROR), ErrorCode::ERROR);
        }
        $request = $request->withAttribute('seller', $sellerInfo);
        Context::set(ServerRequestInterface::class, $request);
        return $handler->handle($request);
    }
}